package com.szgd.service.schedule;

import com.szgd.dao.ecdata.schedule.SegmentProduceScheduleMapper;
import com.szgd.dao.ecdata.schedule.SegmentProduceScheduleMapper;
import com.szgd.service.personnel.AttachService;
import com.szgd.service.sys.SimulateBaseService;
import com.szgd.util.ExcelUtil;
import com.szgd.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SegmentProduceScheduleService extends SimulateBaseService {

    @Autowired
    SegmentProduceScheduleMapper segmentProduceScheduleMapper;
    @Autowired
    AttachService attachService;
    @Autowired
    FileUtil fileUtil;

    public List<Map<String,Object>> getSegmentProduceScheduleList(Map<String, Object> params)
    {
        return  segmentProduceScheduleMapper.getSegmentProduceScheduleList(params);
    }

    public void insertSegmentProduceSchedule(Map<String, Object> params)
    {
        segmentProduceScheduleMapper.insertSegmentProduceSchedule(params);
    }

    public Map<String,Object> getChart(Map<String, Object> params)
    {
        Map<String,Object> res = new HashMap<>();
        List<String> legend = new ArrayList<>();
        legend.add("砼管片（环）");legend.add("钢管片（吨）");
        List<String> xAxis = segmentProduceScheduleMapper.getChartName(null);
        List<List<Double>> series = new ArrayList<>();
        List<List<Long>> current = new ArrayList<>();
        List<List<Long>> cumulative = new ArrayList<>();
        List<List<Long>> total = new ArrayList<>();
        for(int j = 0; j < legend.size(); j++){
            String segmentKind = legend.get(j);
            List<Double> ratetemp = new ArrayList<>();
            List<Long> curtemp = new ArrayList<>();
            List<Long> cumtemp = new ArrayList<>();
            List<Long> tottemp = new ArrayList<>();
            params.put("segmentKind",segmentKind);
            List<Map<String,Object>> mapList = segmentProduceScheduleMapper.getChart(params);
            for(int i = 0; i < mapList.size(); i++){
                ratetemp.add(Double.valueOf(mapList.get(i).get("completeRate").toString()));
                curtemp.add(Long.valueOf(mapList.get(i).get("currentProduce").toString()));
                cumtemp.add(Long.valueOf(mapList.get(i).get("cumulativeProduce").toString()));
                tottemp.add(Long.valueOf(mapList.get(i).get("contractAmount").toString()));
            }
            series.add(ratetemp);
            current.add(curtemp);
            cumulative.add(cumtemp);
            total.add(tottemp);
        }
        res.put("legend",legend);
        res.put("xAxis",xAxis);
        res.put("series",series);
        res.put("current",current);
        res.put("cumulative",cumulative);
        res.put("total",total);
        return res;
    }

    public Map<String,Object> getChartTable(Map<String, Object> params)
    {
        Map<String,Object> res = new HashMap<>();
        List<List<Map<String,Object>>> series = new ArrayList<>();
        List<String> legend = new ArrayList<>();
        legend.add("砼管片（环）");legend.add("钢管片（吨）");
        List<String> xAxis = segmentProduceScheduleMapper.getChartName(null);
        res.put("xAxis",xAxis);
        for(int j = 0; j < legend.size(); j++){
            String segmentKind = legend.get(j);
            params.put("segmentKind",segmentKind);
            List<Map<String,Object>> mapList = segmentProduceScheduleMapper.getChart(params);
            series.add(mapList);
        }
        res.put("series",series);
        return res;
    }

    public boolean importSegmentMainWorkSchedule(MultipartFile[] improtFiles,String loginId) throws IOException, ParseException {
        String failedFilename = null;
        String susscessFilename = null;
        for (MultipartFile file : improtFiles) {//循环

            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            InputStream is = file.getInputStream();
            if (suffix.equalsIgnoreCase("xls")|| suffix.equalsIgnoreCase("xlsx") )//excel文件
            {
                List<Map<String, Object>> segmentResultList = ExcelUtil.readFromSegmentMainWorkScheduleExcel(fileName,is);
                int beginindex = fileName.indexOf("（");
                if (beginindex == -1)
                    beginindex = fileName.indexOf("(");
                int endindex = fileName.indexOf("）");
                if (endindex == -1)
                    endindex = fileName.indexOf(")");
                String dateStr  = "";
                if (beginindex > 0 && endindex > beginindex)
                    dateStr  = fileName.substring(beginindex+1,endindex).replace(".","-");
                else
                {
                    /*SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    dateStr = formatter.format(new Date());*/
                    return  false;
                }
                //log.info("#############关键信息################---mbResultList :"+ JSON.toJSONString());
                Map<String, Object> attachMap = null;
                if(segmentResultList != null && segmentResultList.size() > 0)//有数据，保存excel文件
                {
                    try {
                        is = file.getInputStream();
                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        String date = df.format(new Date());
                        String newFileName = fileUtil.uploadFile(is,fileName,date);

                        Map<String, Object> paramMap = new HashMap<String, Object>();
                        paramMap.put("creator",loginId);
                        paramMap.put("uploader",loginId);
                        paramMap.put("name",newFileName);
                        paramMap.put("type","ATTACH_DOC");
                        paramMap.put("source","ATTACH_SEGMENT_SCHEDULE");
                        attachMap = attachService.saveAttach(paramMap);
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                boolean sussb = segmentResultToTable(segmentResultList,suffix,dateStr,attachMap,loginId);
                if (!sussb && attachMap != null)
                {
                    attachService.deleteAttach(attachMap);
                }

                return sussb;
            }
        }
        return false;
    }

    public boolean segmentResultToTable(List<Map<String, Object>> segmentResultList,String suffix,String dateStr,Map<String, Object> attachMap,String loginId) {
        if (segmentResultList == null || segmentResultList.size() == 0)
            return false;

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("statisticsTime",dateStr);

        List<Map<String,Object>> tempList = getSegmentProduceScheduleList(paramMap);
        if (tempList != null && tempList.size() > 0)
        {
            String attachId = tempList.get(0).get("attachId")==null?null:tempList.get(0).get("attachId").toString();
            if (attachId != null)
            {
                paramMap.put("id",attachId);
                attachService.deleteAttach(paramMap);
            }
            segmentProduceScheduleMapper.deleteSegmentProduceSchedule(paramMap);
        }


        for (int i = 0; i < segmentResultList.size(); i++) {
            Map<String, Object> segmentResultMap = segmentResultList.get(i);
            segmentResultMap.put("statisticsTime",dateStr);

            String  completeRate = segmentResultMap.get("completeRate")==null?"":segmentResultMap.get("completeRate").toString();
            if (completeRate.length()!=0)
            {
                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                completeRate = df.format((float)Float.parseFloat(completeRate)*100);//返回的是String类型
                segmentResultMap.put("completeRate",completeRate);
            }

            segmentResultMap.put("attachId",attachMap.get("id"));
            segmentResultMap.put("creator",loginId);
            segmentProduceScheduleMapper.insertSegmentProduceSchedule(segmentResultMap);
        }
        return true;
    }

    public List<Map<String,Object>> getTime(Map<String, Object> params){
        return segmentProduceScheduleMapper.getTime(params);
    }

    public Double segmentCompleteRateAvg(Map<String, Object> params){
        Double d = segmentProduceScheduleMapper.segmentCompleteRateAvg(params);
        if (d==null)
            d = 0.0;
        return d;

    }
}
